/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.rainbow.file;

import java.io.IOException;
import org.rainbow.udo.UConnection;
import org.rainbow.udo.UdoHandleException;
import org.rainbow.udo.UdoWriter;
import java.io.File;

/**
 *
 * @author hironaga
 */
public abstract class FileWriter extends UdoWriter{

    private static FileCommonHandler commonHandler = new FileCommonHandler();

    protected File tmpFile;

    public FileWriter(UConnection uconn) {
        super(uconn);
    }

    @Override
    synchronized public void commit() throws UdoHandleException {
        try {
            commonHandler.copyFile(tmpFile, uconn.getFile(), commonHandler.DEFAULT_ENCODING);
            tmpFile.delete();
        } catch (IOException ex) {
            throw new UdoHandleException(ex);
        } finally {
            close();
        }
    }

    @Override
    public void rollback() {
        close();
    }

    @Override
    public void close() {
        if(tmpFile != null){
            tmpFile.delete();
        }
    }

    protected File getFile(){
        if(tmpFile != null){
            return tmpFile;
        }
        else{
            return uconn.getFile();
        }
    }

    protected void createTmpFile() throws UdoHandleException{
        if(tmpFile != null){
            return;
        }
        else{
            try {
            tmpFile = commonHandler.createTmpFile(uconn.getFile(), commonHandler.DEFAULT_ENCODING);
            } catch (IOException ex) {
                throw new UdoHandleException(ex);
            }
        }
    }

}
